package com.jxdinfo.hussar.cloud.module.example.tjjc.towerhistorycount.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jxdinfo.hussar.cloud.module.example.tjjc.towercrane.dao.TowerCraneMapper;
import com.jxdinfo.hussar.cloud.module.example.tjjc.towercrane.model.TowerCrane;
import com.jxdinfo.hussar.cloud.module.example.tjjc.towerhistorycount.dao.TowerHistoryCountMapper;
import com.jxdinfo.hussar.cloud.module.example.tjjc.towerhistorycount.model.TowerHistoryCount;
import com.jxdinfo.hussar.cloud.module.example.tjjc.towerhistorycount.service.TowerHistoryCountService;
import com.jxdinfo.hussar.cloud.module.example.tjjc.towerhistorycount.vo.TowerHistoryCountLineVO;
import com.jxdinfo.hussar.cloud.module.example.tjjc.towerhistorycount.vo.TowerHistoryCountPageVO;
import com.jxdinfo.hussar.cloud.module.example.tjjc.towerhistorycount.vo.TowerHistoryCountSearchVO;
import com.jxdinfo.hussar.cloud.module.example.tjjc.towerhistorycount.vo.TowerHistoryCountVO;
import com.jxdinfo.hussar.cloud.module.example.tjjc.util.DateHandleUtil;
import com.jxdinfo.hussar.platform.core.base.apiresult.ApiResponse;
import com.jxdinfo.hussar.platform.core.utils.BeanUtil;
import com.jxdinfo.hussar.support.datasource.annotations.HussarDs;
import com.jxdinfo.hussar.support.mp.base.service.impl.HussarServiceImpl;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 塔机历史统计服务实现类
 */
@Service("tjjc.towerhistorycount.TowerHistoryCountServiceImpl")
@HussarDs("master")
public class TowerHistoryCountServiceImpl extends HussarServiceImpl<TowerHistoryCountMapper, TowerHistoryCount> implements TowerHistoryCountService {

    private static final Logger logger = LoggerFactory.getLogger(TowerHistoryCountServiceImpl.class);

    private static final String RETURN_CODE = "0";

    @Autowired
    private TowerHistoryCountMapper towerHistoryCountMapper;
    @Autowired
    private TowerCraneMapper towerCraneMapper;

    @Override
    public ApiResponse<List<TowerHistoryCountLineVO>> findByLine(TowerHistoryCountSearchVO towerHistoryCountSearchVO) {
        QueryWrapper<TowerCrane> wrapper = new QueryWrapper<>();
        wrapper.eq("ty_project_code", towerHistoryCountSearchVO.getTyProjectCode());
        wrapper.eq("ty_delete_status", 0);
        if(ObjectUtils.isNotEmpty(towerHistoryCountSearchVO.getTowerId())) {
            String[] towerIds = towerHistoryCountSearchVO.getTowerId().split(",");
            wrapper.in("id", towerIds);
        }
        List<TowerCrane> towers = towerCraneMapper.selectList(wrapper);

        //封装查询条件
        QueryWrapper<TowerHistoryCount> towerHistoryCountWrapper = new QueryWrapper<>();
        towerHistoryCountWrapper.eq("ty_project_code", towerHistoryCountSearchVO.getTyProjectCode());
        if(ObjectUtils.isNotEmpty(towerHistoryCountSearchVO.getCountDateStart())) {
            towerHistoryCountWrapper.ge("count_date", towerHistoryCountSearchVO.getCountDateStart());
        }
        if(ObjectUtils.isNotEmpty(towerHistoryCountSearchVO.getCountDateEnd())) {
//            towerHistoryCountPageQueryVO.setCountDateEnd(DateUtils.nDaysAfter(1, towerHistoryCountPageQueryVO.getCountDateEnd()));
            towerHistoryCountWrapper.lt("count_date", towerHistoryCountSearchVO.getCountDateEnd());
        }
        List<String> towerIdList = towers.stream().map(TowerCrane::getId).collect(Collectors.toList());
        towerHistoryCountWrapper.in("tower_id", towerIdList);
        towerHistoryCountWrapper.orderByAsc("count_date");

        List<TowerHistoryCount> list = towerHistoryCountMapper.selectList(towerHistoryCountWrapper);

        List<TowerHistoryCountVO> historyList = BeanUtil.copyToList(list, TowerHistoryCountVO.class);
        Map<String, List<TowerHistoryCountVO>> map = historyList.stream().collect(Collectors.groupingBy(data -> data.getCountDate().format(DateTimeFormatter.ofPattern("yyyyMMdd"))));

        List<TowerHistoryCountLineVO> dataList = new ArrayList<>();

        //todo 缺DateHandleUtil工具类
        List<String> dateList = DateHandleUtil.completionDateList(towerHistoryCountSearchVO.getCountDateStart(), towerHistoryCountSearchVO.getCountDateEnd(), map.keySet());

        for(String date : dateList) {
            TowerHistoryCountLineVO line = new TowerHistoryCountLineVO();
            line.setCountDate(date);

            List<TowerHistoryCountVO> lineData = map.get(date);
            if(lineData == null) {
                lineData = new ArrayList<>();
            }

            Set<String> towerHistoryCountSet = lineData.stream().map(TowerHistoryCountVO::getTowerId).collect(Collectors.toSet());
            for (TowerCrane tower : towers) {
                if (!towerHistoryCountSet.contains(tower.getId())) {
                    TowerHistoryCountVO towerHistoryCountDto = new TowerHistoryCountVO();
                    towerHistoryCountDto.setTowerId(tower.getId());
                    towerHistoryCountDto.setTowerName(tower.getTowerName());
                    towerHistoryCountDto.setWorkNum(0);
                    towerHistoryCountDto.setWorkWeight(BigDecimal.ZERO.doubleValue());
                    lineData.add(towerHistoryCountDto);
                }
            }
            line.setDataList(lineData);
            dataList.add(line);
        }

        return ApiResponse.success(dataList);
    }

    @Override
    public ApiResponse<TowerHistoryCountPageVO> findByPage(TowerHistoryCountSearchVO towerHistoryCountSearchVO) {
        QueryWrapper<TowerHistoryCount> wrapper = new QueryWrapper<>();
        Page<TowerHistoryCount> page = new Page<>();
        page.setPages(towerHistoryCountSearchVO.getPage());
        page.setSize(towerHistoryCountSearchVO.getRows());

        if(ObjectUtils.isNotEmpty(towerHistoryCountSearchVO.getTyProjectCode())) {
            wrapper.eq("ty_project_code", towerHistoryCountSearchVO.getTyProjectCode());
        }
        if(ObjectUtils.isNotEmpty(towerHistoryCountSearchVO.getCountDateStart())) {
            wrapper.ge("count_date", towerHistoryCountSearchVO.getCountDateStart());
        }
        if(ObjectUtils.isNotEmpty(towerHistoryCountSearchVO.getCountDateEnd())) {
            Date endTime = DateUtil.endOfDay(towerHistoryCountSearchVO.getCountDateEnd());
            wrapper.le("count_date", endTime);
        }
        if(StrUtil.isNotEmpty(towerHistoryCountSearchVO.getTowerId())) {
            String[] towerIds = towerHistoryCountSearchVO.getTowerId().split(",");
            wrapper.in("tower_id", towerIds);
        } else {
            QueryWrapper<TowerCrane> wrapperTower = new QueryWrapper<>();
            wrapperTower.eq("ty_project_code", towerHistoryCountSearchVO.getTyProjectCode());
            wrapperTower.eq("ty_delete_status", 0);
            List<TowerCrane> towers = towerCraneMapper.selectList(wrapperTower);
            List<String> towerIds = towers.stream().map(TowerCrane::getId).collect(Collectors.toList());
            wrapper.in("tower_id", towerIds);
        }

        wrapper.orderByDesc("count_date");

        Page<TowerHistoryCount> countPage = towerHistoryCountMapper.selectPage(page, wrapper);

        TowerHistoryCountPageVO towerHistoryCountPageVO = new TowerHistoryCountPageVO();
        towerHistoryCountPageVO.setData(countPage.getRecords());
        towerHistoryCountPageVO.setCode(RETURN_CODE);
        towerHistoryCountPageVO.setCount(countPage.getTotal());

        return ApiResponse.success(towerHistoryCountPageVO);
    }

    @Override
    public ApiResponse<List<TowerHistoryCountVO>> findByList(TowerHistoryCountSearchVO towerHistoryCountSearchVO) {
        QueryWrapper<TowerHistoryCount> wrapper = new QueryWrapper<>();
        if(ObjectUtils.isNotEmpty(towerHistoryCountSearchVO.getTyProjectCode())) {
            wrapper.eq("ty_project_code", towerHistoryCountSearchVO.getTyProjectCode());
        }
        if(ObjectUtils.isNotEmpty(towerHistoryCountSearchVO.getCountDateStart())) {
            wrapper.ge("count_date", towerHistoryCountSearchVO.getCountDateStart());
        }
        if(ObjectUtils.isNotEmpty(towerHistoryCountSearchVO.getCountDateEnd())) {
            wrapper.le("count_date", towerHistoryCountSearchVO.getCountDateEnd());
        }

        wrapper.orderByDesc("count_date");

        List<TowerHistoryCount> list = towerHistoryCountMapper.selectList(wrapper);

        List<TowerHistoryCountVO> towerHistoryCountVOS = BeanUtil.copyToList(list, TowerHistoryCountVO.class);

        return ApiResponse.success(towerHistoryCountVOS);
    }
}
